package com.kexun.config.websocket;

import com.alibaba.fastjson.JSON;
import com.kexun.entity.DO.Manage;
import com.kexun.mapper.db1.ManageMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Component
public class MessageHandler {
    @Autowired
    private ManageMapper manageMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    public void sendMessage(String user, String content) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("from", "system");
        map.put("content", content);
        map.put("type", 2);
        map.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        String msg = JSON.toJSONString(map);
        if (StringUtils.isEmpty(user)) {
            List<Manage> manages = manageMapper.selectList(null);
            for (Manage manage : manages) {
                if (manage.getOpenPush() == 0) {
                    webSocketServer.sendInfo(msg, manage.getManageName());
                }
            }
        } else {
            webSocketServer.sendInfo(msg, user);
        }
    }

}
